import datetime

from appBackend.models import CurrencyExchangeRateRecords
import logging

logger = logging.getLogger("log")

def get_newest_rate():
    import requests

    cookies = {
        '_ulta_id.CM-Prod.e9dc': 'c2c03c82cf37b052',
        '_ulta_ses.CM-Prod.e9dc': '61706b5aca0b2d27',
        'AlteonP10': 'CJqKQyw/F6ygkqpSIPAvbA$$',
        'apache': 'bbfde8c184f3e1c6074ffab28a313c87',
        'ags': '2a1ba4d47b619c011c19c1cc4b3c0c32',
        'lss': 'f7cb2cf4b1607aec30e411e90d47c685',
        'isLogin': '0',
    }

    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Connection': 'keep-alive',
        # 'Content-Length': '0',
        # 'Cookie': '_ulta_id.CM-Prod.e9dc=c2c03c82cf37b052; _ulta_ses.CM-Prod.e9dc=61706b5aca0b2d27; AlteonP10=CJqKQyw/F6ygkqpSIPAvbA$$; apache=bbfde8c184f3e1c6074ffab28a313c87; ags=2a1ba4d47b619c011c19c1cc4b3c0c32; lss=f7cb2cf4b1607aec30e411e90d47c685; isLogin=0',
        'Origin': 'https://www.chinamoney.com.cn',
        'Referer': 'https://www.chinamoney.com.cn/chinese/sddshl/',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
        'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
    }

    params = {
        't': '1714635950647',
    }

    response = requests.post(
        'https://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/sdds-exch-rate.json',
        params=params,
        cookies=cookies,
        headers=headers,
    )
    result = response.json()
    print(result)
    records = result['records']
    for record in records:
        print(f"vrtName:{record['vrtName']} - price:{record['price']}")

    currency_exchange_rate_records = CurrencyExchangeRateRecords(data=records,
                                                                 upload_time=datetime.datetime.now())
    currency_exchange_rate_records.save()
    logger.info(f"获取最新货币兑换数据完成")


# if __name__ == '__main__':
#     get_newest_rate()